package com.mars.miaosha.controller;

import com.mars.miaosha.domain.MiaoshaUser;
import com.mars.miaosha.result.Result;
import com.mars.miaosha.service.GoodsService;
import com.mars.miaosha.service.MiaoshaUserService;
import com.mars.miaosha.service.UserService;
import com.mars.miaosha.vo.GoodsVo;
import com.mars.miaosha.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * @author MARS
 * @date 2018/5/8
 */

@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    private MiaoshaUserService miaoshaUserService;

    @Autowired
    private GoodsService goodsService ;


    @RequestMapping("/to_list")
    public String toList(Model model,MiaoshaUser msUser){
//        if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)){
//            return "login";
//        }
//
//        // 根据优先级获取token信息
//        String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
//        MiaoshaUser msUser = miaoshaUserService.getByToken(response,token);
        model.addAttribute("user",msUser);
        // 获取商品列表信息
        List<GoodsVo> goodsVoList = goodsService.getGoodsList();
        model.addAttribute("goodsList",goodsVoList);
        return "goods_list";
    }

    /**
     * 生成随机订单的id:snownflake算法
     *
     * 获取商品详情
     * @return
     */
    @RequestMapping("/to_detail/{goodsId}")
    public String toDtail(Model model, MiaoshaUser msUser, @PathVariable("goodsId")long goodsId){
        model.addAttribute("user",msUser);
        GoodsVo goodsVo = goodsService.getGoodsByGoodsId(goodsId);

        model.addAttribute("goods",goodsVo);

        // 获取秒杀开始、结束的时间
        long startAt = goodsVo.getStartDate().getTime();
        long endAt = goodsVo.getEndDate().getTime();
        long now = System.currentTimeMillis();

        // 设置秒杀状态
        int miaoshaStatus = 0;
        // 剩余多长时间开始
        int renmainSeconds = 0;

        if (now < startAt) {//秒杀还未开始
            miaoshaStatus = 0;
            renmainSeconds = (int)(startAt - now)/1000;
        } else if (now > endAt) {//秒杀已经结束
            miaoshaStatus = 2;
            renmainSeconds = -1;
        } else { //秒杀进行中
            miaoshaStatus = 1;
            renmainSeconds = 0;
        }

        model.addAttribute("miaoshaStatus",miaoshaStatus);
        model.addAttribute("renmainSeconds",renmainSeconds);

        return "goods_detail";
    }


}
